package org.iamd.security;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;

/**
 * Callback handler работещ с потребителко име и парола.
 * 
 * @author И. Атанасов
 */
public class UserPasswordCallbackHandler implements CallbackHandler {

	/** Парола. */
	private String password;

	/** Потребителско име. */
	private String username;

	/**
	 * Стандартен конструктор.
	 * 
	 * @param username
	 *            потребителско име
	 * @param password
	 *            парола
	 */
	public UserPasswordCallbackHandler(String username, String password) {
		this.username = username;
		this.password = password;
	}

	/**
	 * Работи само за {@link NameCallback} и за {@link PasswordCallback}, като
	 * им set-ва съответно потребителското име и паролата.
	 * 
	 * @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[])
	 */
	@Override
	public void handle(Callback[] callbacks) {
		for (Callback callback : callbacks) {
			try {
				((NameCallback) callback).setName(this.username);
			} catch (ClassCastException e) {
				try {
					((PasswordCallback) callback).setPassword(this.password.toCharArray());
				} catch (ClassCastException e2) {
					// do nothing
				}
			}
		}
	}

}